package com.wisdom.view;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.json.JSONException;
import org.json.JSONObject;
import org.sipdroid.sipua.ui.Receiver;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.AlertDialog.Builder;
import android.app.ProgressDialog;
import android.content.AsyncQueryHandler;
import android.content.ContentResolver;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.database.Cursor;
import android.media.AudioManager;
import android.media.SoundPool;
import android.net.ConnectivityManager;
import android.net.NetworkInfo.State;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.provider.CallLog;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.view.Gravity;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.View.OnLongClickListener;
import android.widget.AbsListView;
import android.widget.AbsListView.OnScrollListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.Button;
import android.widget.ImageButton;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.Toast;

import com.bluecall.sipua.R;
import com.wisdom.VoiceApplication;
import com.wisdom.bean.CallLogBean;
import com.wisdom.tools.CCPConfig;
import com.wisdom.tools.HttpUtil;
import com.wisdom.ui.MenuHorizontalScrollView;
import com.wisdom.view.adapter.HomeDialAdapter;
import com.wisdom.view.adapter.T9Adapter;
import com.wisdom.voip.CallOutActivity;

public class HomeDialActivity extends Activity implements OnClickListener {
	private MenuHorizontalScrollView scrollView;
	private AsyncQueryHandler asyncQuery;

	private HomeDialAdapter adapter;
	private ListView callLogList;
	private String prefix = "11";
	private List<CallLogBean> list;

	private LinearLayout bohaopan;
	private LinearLayout keyboard_show_ll;
	private Button keyboard_show;
	private Button menuBtn;
	private Button phone_view;
	private ImageButton delete;
	private Map<Integer, Integer> map = new HashMap<Integer, Integer>();
	private SoundPool spool;
	private AudioManager am = null;

	private VoiceApplication application;
	private ListView listView;
	private T9Adapter t9Adapter;
	private SharedPreferences mSharedPreferences;
	private int mCallMode;
	
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.home_dial_page);

		mSharedPreferences = getSharedPreferences(DialSettingActivity.SHAREDPREFERENCE_DB, MODE_PRIVATE);
		mCallMode = mSharedPreferences.getInt(DialSettingActivity.SHAREDPREFERENCE_CALLSETTING, DialSettingActivity.SHAREDPREFERENCE_WISTOMCALL);
		application = (VoiceApplication) getApplication();
		listView = (ListView) findViewById(R.id.contact_list);

		bohaopan = (LinearLayout) findViewById(R.id.bohaopan);
		keyboard_show_ll = (LinearLayout) findViewById(R.id.keyboard_show_ll);
		keyboard_show = (Button) findViewById(R.id.keyboard_show);
		callLogList = (ListView) findViewById(R.id.call_log_list);
		asyncQuery = new MyAsyncQueryHandler(getContentResolver());

		keyboard_show.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				dialPadShow();
			}

		});

		am = (AudioManager) getSystemService(Context.AUDIO_SERVICE);
		spool = new SoundPool(11, AudioManager.STREAM_SYSTEM, 5);
		map.put(0, spool.load(this, R.raw.dtmf0, 0));
		map.put(1, spool.load(this, R.raw.dtmf1, 0));
		map.put(2, spool.load(this, R.raw.dtmf2, 0));
		map.put(3, spool.load(this, R.raw.dtmf3, 0));
		map.put(4, spool.load(this, R.raw.dtmf4, 0));
		map.put(5, spool.load(this, R.raw.dtmf5, 0));
		map.put(6, spool.load(this, R.raw.dtmf6, 0));
		map.put(7, spool.load(this, R.raw.dtmf7, 0));
		map.put(8, spool.load(this, R.raw.dtmf8, 0));
		map.put(9, spool.load(this, R.raw.dtmf9, 0));
		map.put(11, spool.load(this, R.raw.dtmf11, 0));
		map.put(12, spool.load(this, R.raw.dtmf12, 0));

		phone_view = (Button) findViewById(R.id.phone_view);
		phone_view.setOnClickListener(this);
		phone_view.addTextChangedListener(new TextWatcher() {
			public void onTextChanged(CharSequence s, int start, int before,
					int count) {
				if (null == application.getContactBeanList()
						|| application.getContactBeanList().size() < 1
						|| "".equals(s.toString())) {
					listView.setVisibility(View.INVISIBLE);
					callLogList.setVisibility(View.VISIBLE);
				} else {
					if (null == t9Adapter) {
						t9Adapter = new T9Adapter(HomeDialActivity.this);
						t9Adapter.assignment(application.getContactBeanList());
						// TextView tv = new TextView(HomeDialActivity.this);
						// tv.setBackgroundResource(R.drawable.dial_input_bg2);
						// listView.addFooterView(tv);
						listView.setAdapter(t9Adapter);
						listView.setTextFilterEnabled(true);
						listView.setOnScrollListener(new OnScrollListener() {
							public void onScrollStateChanged(AbsListView view,
									int scrollState) {
								if (scrollState == OnScrollListener.SCROLL_STATE_TOUCH_SCROLL) {
									if (bohaopan.getVisibility() == View.VISIBLE) {
										bohaopan.setVisibility(View.GONE);
										keyboard_show_ll
												.setVisibility(View.VISIBLE);
									}
								}
							}

							public void onScroll(AbsListView view,
									int firstVisibleItem, int visibleItemCount,
									int totalItemCount) {
							}
						});
					} else {
						callLogList.setVisibility(View.INVISIBLE);
						listView.setVisibility(View.VISIBLE);
						t9Adapter.getFilter().filter(s);
					}
				}
			}

			public void beforeTextChanged(CharSequence s, int start, int count,
					int after) {
			}

			public void afterTextChanged(Editable s) {
			}
		});
		delete = (ImageButton) findViewById(R.id.delete);
		delete.setOnClickListener(this);
		delete.setOnLongClickListener(new OnLongClickListener() {
			public boolean onLongClick(View v) {
				phone_view.setText("");
				return false;
			}
		});
		for (int i = 0; i < 12; i++) {
			View v = findViewById(R.id.dialNum1 + i);
			v.setOnClickListener(this);
		}
		init();

	}
	

	@Override
	protected void onResume() {
		mCallMode = mSharedPreferences.getInt(DialSettingActivity.SHAREDPREFERENCE_CALLSETTING, 0);
		super.onResume();
	}
	
	public void onClick(View v) {
		switch (v.getId()) {
		case R.id.dialNum0:
			if (phone_view.getText().length() < 12) {
				play(1);
				input(v.getTag().toString());
			}
			break;
		case R.id.dialNum1:
			if (phone_view.getText().length() < 12) {
				play(1);
				input(v.getTag().toString());
			}
			break;
		case R.id.dialNum2:
			if (phone_view.getText().length() < 12) {
				play(2);
				input(v.getTag().toString());
			}
			break;
		case R.id.dialNum3:
			if (phone_view.getText().length() < 12) {
				play(3);
				input(v.getTag().toString());
			}
			break;
		case R.id.dialNum4:
			if (phone_view.getText().length() < 12) {
				play(4);
				input(v.getTag().toString());
			}
			break;
		case R.id.dialNum5:
			if (phone_view.getText().length() < 12) {
				play(5);
				input(v.getTag().toString());
			}
			break;
		case R.id.dialNum6:
			if (phone_view.getText().length() < 12) {
				play(6);
				input(v.getTag().toString());
			}
			break;
		case R.id.dialNum7:
			if (phone_view.getText().length() < 12) {
				play(7);
				input(v.getTag().toString());
			}
			break;
		case R.id.dialNum8:
			if (phone_view.getText().length() < 12) {
				play(8);
				input(v.getTag().toString());
			}
			break;
		case R.id.dialNum9:
			if (phone_view.getText().length() < 12) {
				play(9);
				input(v.getTag().toString());
			}
			break;
		case R.id.dialx:
			if (phone_view.getText().length() < 12) {
				play(11);
				input(v.getTag().toString());
			}
			break;
		case R.id.dialj:
			if (phone_view.getText().length() < 12) {
				play(12);
				input(v.getTag().toString());
			}
			break;
		case R.id.delete:
			delete();
			break;
		case R.id.phone_view:
			if (phone_view.getText().toString().length() >= 4) {
				call(phone_view.getText().toString());
//				Uri uri = Uri.parse("tel:" + phone_view.getText().toString());
//				Intent it = new Intent(Intent.ACTION_CALL, uri);
//				HomeDialActivity.this.startActivity(it);
			}
			break;
		default:
			break;
		}
	}

	private class MyAsyncQueryHandler extends AsyncQueryHandler {

		public MyAsyncQueryHandler(ContentResolver cr) {
			super(cr);
			// TODO Auto-generated constructor stub
		}

		protected void onQueryComplete(int token, Object cookie, Cursor cursor) {
			if (cursor != null && cursor.getCount() > 0) {
				list = new ArrayList<CallLogBean>();
				SimpleDateFormat sfd = new SimpleDateFormat("MM-dd hh:mm");
				Date date;
				cursor.moveToFirst();
				for (int i = 0; i < cursor.getCount(); i++) {
					cursor.moveToPosition(i);
					date = new Date(cursor.getLong(cursor
							.getColumnIndex(CallLog.Calls.DATE)));
					String number = cursor.getString(cursor
							.getColumnIndex(CallLog.Calls.NUMBER));
					int type = cursor.getInt(cursor
							.getColumnIndex(CallLog.Calls.TYPE));
					String cachedName = cursor.getString(cursor
							.getColumnIndex(CallLog.Calls.CACHED_NAME));
					int id = cursor.getInt(cursor
							.getColumnIndex(CallLog.Calls._ID));

					CallLogBean clb = new CallLogBean();
					clb.setId(id);
					clb.setNumber(number);
					clb.setName(cachedName);
					if (null == cachedName || "".equals(cachedName)) {
						clb.setName(number);
					}
					clb.setType(type);
					clb.setDate(sfd.format(date));

					list.add(clb);
				}
				if (list.size() > 0) {
					setAdapter(list);
				}
			}
		}

	}

	private void init() {
		Uri uri = CallLog.Calls.CONTENT_URI;

		String[] projection = { CallLog.Calls.DATE, CallLog.Calls.NUMBER,
				CallLog.Calls.TYPE, CallLog.Calls.CACHED_NAME,
				CallLog.Calls._ID }; // 查询的列
		asyncQuery.startQuery(0, null, uri, projection, null, null,
				CallLog.Calls.DEFAULT_SORT_ORDER);
	}

	private String[] lianxiren1 = new String[] { "网络直拨", "网络回拨", "发送短信" };

	// private String[] lianxiren1 = new String[] { "网络直拨","网络回拨","拨打电话",
	// "发送短信", "查看详细"};
	private void setAdapter(List<CallLogBean> list) {
		adapter = new HomeDialAdapter(this, list);

		callLogList.setAdapter(adapter);
		callLogList.setOnScrollListener(new OnScrollListener() {

			@Override
			public void onScroll(AbsListView view, int firstVisibleItem,
					int visibleItemCount, int totalItemCount) {

			}

			@Override
			public void onScrollStateChanged(AbsListView view, int scrollState) {
				if (scrollState == OnScrollListener.SCROLL_STATE_TOUCH_SCROLL) {
					// 滚动不自动隐藏拨号盘了，怕很多用户不会打开拨号盘
					// if(bohaopan.getVisibility()==View.VISIBLE){
					// bohaopan.setVisibility(View.GONE);
					// keyboard_show_ll.setVisibility(View.VISIBLE);
					// }
				}

			}

		});
		callLogList.setOnItemClickListener(new OnItemClickListener() {
			public void onItemClick(AdapterView<?> parent, View view,
					int position, long id) {

				CallLogBean clb = (CallLogBean) adapter.getItem(position);
				showContactDialog(lianxiren1, clb, position);
			}
		});
	}

	private String getSMSThreadId(String adddress) {
		Cursor cursor = null;
		ContentResolver contentResolver = getContentResolver();
		cursor = contentResolver.query(Uri.parse("content://sms"), SMS_COLUMNS,
				" address like '%" + adddress + "%' ", null, null);
		String threadId = "";
		if (cursor == null || cursor.getCount() > 0) {
			cursor.moveToFirst();
			threadId = cursor.getString(0);
			cursor.close();
			return threadId;
		} else {
			cursor.close();
			return threadId;
		}
	}

	public static String[] SMS_COLUMNS = new String[] { "thread_id" };

	private void showContactDialog(final String[] arg, final CallLogBean cb,
			final int position) {
		call(cb.getNumber());
		// new AlertDialog.Builder(this).setTitle(cb.getName()).setItems(arg,
		// new DialogInterface.OnClickListener(){
		// public void onClick(DialogInterface dialog, int which){
		//
		// Uri uri = null;
		// String toPhone = cb.getNumber();
		// String threadId = getSMSThreadId(cb.getNumber());
		// Map<String, String> map = new HashMap<String, String>();
		// Intent it=null;
		// switch(which){
		// case 0://网络直拨
		// if(!checkLogin())return;
		// startVoipCall(VOIP_CALL_TYPE_DIRECT_TALK,toPhone);
		// break;
		// case 1://网络回拨
		//
		// if(!checkLogin())return;
		// startVoipCall(VOIP_CALL_TYPE_BACK_TALK,toPhone);
		// break;
		// // case 2://打电话
		// // toPhone = cb.getNumber();
		// // uri = Uri.parse("tel:" + toPhone);
		// // it = new Intent(Intent.ACTION_CALL, uri);
		// // startActivity(it);
		// // break;
		//
		// case 2://发短息
		//
		// threadId = getSMSThreadId(cb.getNumber());
		//
		// map = new HashMap<String, String>();
		// map.put("phoneNumber", cb.getNumber());
		// map.put("threadId", threadId);
		// BaseIntentUtil.intentSysDefault(HomeDialActivity.this,
		// MessageBoxList.class, map);
		// break;
		//
		// case 4:// 查看详细 修改联系人资料
		//
		// uri = ContactsContract.Contacts.CONTENT_URI;
		// Uri personUri = ContentUris.withAppendedId(uri, cb.getId());
		// Intent intent2 = new Intent();
		// intent2.setAction(Intent.ACTION_VIEW);
		// intent2.setData(personUri);
		// startActivity(intent2);
		// break;
		//
		//
		// }}
		// }).show();
	}

	Boolean checkLogin() {
		if (!CCPConfig.check()) {
			Toast.makeText(HomeDialActivity.this, "请先注册或者登录！.",
					Toast.LENGTH_SHORT).show();
			startActivity(new Intent(HomeDialActivity.this,
					WelcomeActivity.class));
			return false;
		}
		return true;

	}

	public void dialPadShow() {
		if (bohaopan.getVisibility() == View.VISIBLE) {
			bohaopan.setVisibility(View.GONE);
			keyboard_show_ll.setVisibility(View.VISIBLE);
		} else {
			bohaopan.setVisibility(View.VISIBLE);
			keyboard_show_ll.setVisibility(View.INVISIBLE);
		}
	}

	private void play(int id) {
		int max = am.getStreamMaxVolume(AudioManager.STREAM_MUSIC);
		int current = am.getStreamVolume(AudioManager.STREAM_MUSIC);

		float value = (float) 0.7 / max * current;
		spool.setVolume(spool.play(id, value, value, 0, 0, 1f), value, value);
	}

	private void input(String str) {
		String p = phone_view.getText().toString();
		phone_view.setText(p + str);
	}

	private void delete() {
		String p = phone_view.getText().toString();
		if (p.length() > 0) {
			phone_view.setText(p.substring(0, p.length() - 1));
		}
	}

	public void call(final String phone) {
		// Uri uri = Uri.parse("tel:" + phone);
		// Intent it = new Intent(Intent.ACTION_CALL, uri);
		// startActivity(it);
		switch (mCallMode) {
		case DialSettingActivity.SHAREDPREFERENCE_CALLBACK:
			startVoipCall(VOIP_CALL_TYPE_BACK_TALK, phone);
			break;
		case DialSettingActivity.SHAREDPREFERENCE_DIRECTCALL:
			startVoipCall(VOIP_CALL_TYPE_DIRECT_TALK, phone);
			break;
		case DialSettingActivity.SHAREDPREFERENCE_EACHTIME:
			getMutiItemDialog(phone).show();
			break;
		case DialSettingActivity.SHAREDPREFERENCE_WISTOMCALL:
			ConnectivityManager conMan = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
			State wifi = conMan.getNetworkInfo(ConnectivityManager.TYPE_WIFI)
					.getState();
			if (wifi == State.CONNECTED || wifi == State.CONNECTING) {
				// 直拨
				startVoipCall(VOIP_CALL_TYPE_DIRECT_TALK, phone);
				return;
			} else {
				startVoipCall(VOIP_CALL_TYPE_BACK_TALK, phone);
				return;
				// 回拨
			}
		}

		// new AlertDialog.Builder(this).setTitle(phone).setItems(new
		// String[]{"网络直拨","网络回拨","发短信"},
		// new DialogInterface.OnClickListener(){
		// public void onClick(DialogInterface dialog, int which){
		//
		// Uri uri = null;
		// String threadId = getSMSThreadId(phone);
		// Map<String, String> map = new HashMap<String, String>();
		// switch(which){
		// case 0://网络直拨
		// startVoipCall(VOIP_CALL_TYPE_DIRECT_TALK,phone);
		// break;
		//
		// // case 2://打电话
		// //
		// // String threadId = getSMSThreadId(phone);
		// //
		// // Map<String, String> map = new HashMap<String, String>();
		// // map.put("phoneNumber", phone);
		// // map.put("threadId", threadId);
		// // BaseIntentUtil.intentSysDefault(HomeDialActivity.this,
		// MessageBoxList.class, map);
		// // break;
		// case 1://网络回拨
		// startVoipCall(VOIP_CALL_TYPE_BACK_TALK,phone);
		// break;
		//
		// case 2://发短息
		//
		// threadId = getSMSThreadId(phone);
		//
		// map = new HashMap<String, String>();
		// map.put("phoneNumber", phone);
		// map.put("threadId", threadId);
		// BaseIntentUtil.intentSysDefault(HomeDialActivity.this,
		// MessageBoxList.class, map);
		// break;
		//
		// }}
		// }).show();
	}

	private static final int VOIP_CALL_TYPE_BACK_TALK = 203;
	private static final int VOIP_CALL_TYPE_DIRECT_TALK = 204;

	void startVoipCall(int mCallType, String phoneStr) {

		if (TextUtils.isEmpty(phoneStr)) {
			VoiceApplication.getInstance().showToast(R.string.edit_input_empty);
			return;
		}
		tyoe = mCallType;
		phoneto = phoneStr;
		Intent intent = new Intent(this, CallOutActivity.class);
		// 直播电话
		/*
		 * if(!phoneStr.startsWith("0")&&!phoneStr.startsWith("1")){ //判断输入合法性
		 * VoiceApplication
		 * .getInstance().showToast(getString(R.string.network_dial_number_format
		 * )); return; }
		 */
		if(mCallType == VOIP_CALL_TYPE_DIRECT_TALK){
			initCall(phoneto);
		}else if(mCallType == VOIP_CALL_TYPE_BACK_TALK){
			callBackCall(phoneStr);
		}

	}

	private static AlertDialog m_AlertDlg;

	private void initCall(String mPhoneNumber) {
		if (!mPhoneNumber.startsWith("11")) {
			mPhoneNumber = "11" + mPhoneNumber;
		}
		String target = mPhoneNumber;
		if (m_AlertDlg != null) {
			m_AlertDlg.cancel();
		}
		if (target.length() == 0)
			m_AlertDlg = new AlertDialog.Builder(this)
					.setMessage(R.string.empty).setTitle(R.string.app_name)
					.setIcon(R.drawable.icon22).setCancelable(true).show();
		else if (!Receiver.engine(this).call(target, true))
			m_AlertDlg = new AlertDialog.Builder(this)
					.setMessage(R.string.notfast).setTitle(R.string.app_name)
					.setIcon(R.drawable.icon22).setCancelable(true).show();
		return;
	}

	private void callBackCall(String toTelNum) {
		ProgressDialog mDialog;
		mDialog = new ProgressDialog(HomeDialActivity.this);
		mDialog.setMessage(getString(R.string.dialoglogon_message_text));
		mDialog.setCanceledOnTouchOutside(false);
		mDialog.show();
		String srcPhone = CCPConfig.Src_phone;
		JSONObject object;
		try {
			object = new JSONObject("{ToPhone:\"" + toTelNum + "\",SrcPhone:\""
					+ srcPhone + "\",UserName:\"" + srcPhone + "\"}");

			JSONObject data = HttpUtil.post(MakeCallbackActivity.callbackUrl,
					object);
			mDialog.cancel();
			if (data == null) {
				Toast toast = Toast.makeText(this, "未知错误", Toast.LENGTH_LONG);
				toast.setGravity(Gravity.TOP, 0, 50);
				toast.show();
				return;
			}
			if (data.getBoolean("success")) {
				Toast toast = Toast.makeText(this,
						"回拨成功，请注意接听来电" + data.getString("message"),
						Toast.LENGTH_LONG);
				toast.setGravity(Gravity.TOP, 0, 50);
				toast.show();
				// Toast.makeText(getApplicationContext(),
				// "回拨成功，请注意接听来电"+data.getString("message"),Toast.LENGTH_SHORT).show();
			} else {
				Toast toast = Toast.makeText(this,
						"登陆失败：" + data.getString("message"), Toast.LENGTH_LONG);
				toast.setGravity(Gravity.TOP, 0, 50);
				toast.show();
				// Toast.makeText(getApplicationContext(),
				// "登陆失败："+data.getString("message"),Toast.LENGTH_SHORT).show();
			}
		} catch (JSONException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}

	String phoneto = "";
	int tyoe = 0;
	private Handler helperHandler = new Handler() {
		@Override
		public void handleMessage(Message msg) {
			startVoipCall(tyoe, phoneto);
		}
	};

	public AlertDialog getMutiItemDialog(final String tel) {
		String[] content = { "回拨方式", "直播方式" };

		Builder builder = new Builder(this);
		builder.setItems(content, new DialogInterface.OnClickListener() {
			@Override
			public void onClick(DialogInterface dialog, int which) {
				switch (which) {
				case 0:
					startVoipCall(VOIP_CALL_TYPE_BACK_TALK, tel);
					break;
				case 1:
					startVoipCall(VOIP_CALL_TYPE_DIRECT_TALK, tel);
					break;
				default:
					break;
				}
			}
		});
		return builder.create();
	}

}
